package lecode;


/**
 * 两数相加
 */
public class 两数相加2 {

    public static void main(String[] args) {
        MyNode myNode1 = new MyNode(2, new MyNode(4, new MyNode(3, null)));
        System.out.println(myNode1);
        MyNode myNode2 = new MyNode(5, new MyNode(6, new MyNode(4, null)));
        System.out.println(myNode2);
        MyNode myNode = addTwoNumbers(myNode1, myNode2);
        System.out.println(myNode.toString());


    }

    public static MyNode addTwoNumbers(MyNode l1, MyNode l2) {
        // 构造哑巴节点 dummy，最后返回 dummy.next, 以方便处理新链表的头节点。
        MyNode dummy = new MyNode(0);
        MyNode node = dummy; // node 一直会变化（前进）
        int carrier = 0; // 进位

        // 只要有没走到头的链表或者进位不为 0 就一直前进。
        while (l1 != null || l2 != null || carrier != 0) {
            // 求和，考虑可能有链表走到头
            int sum = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + carrier;

            // 在尾部添加节点
            node.next = new MyNode(sum % 10);
            node = node.next;

            // 更新进位，并向两个链表尾部前进
            carrier = sum / 10;
            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next;
        }

        return dummy.next;
    }
}


class MyNode {
    int val;
    MyNode next;

    public MyNode() {
    }

    public MyNode(int val) {
        this.val = val;
        this.next = null;
    }
    public MyNode(int val, MyNode next) {
        this.val = val;
        this.next = next;
    }

    public int getVal() {
        return val;
    }

    public int setVal(int val) {
        this.val = val;
        return val;
    }

    public MyNode getNext() {
        return next;
    }

    public MyNode setNext(MyNode next) {
        this.next = next;
        return next;
    }

    @Override
    public String toString() {
        return "MyNode{" +
                "val=" + val +
                ", next=" + next +
                '}';
    }
}
